package com.google.jessewilson.codesearch.util;

/**
 * Convert a String like "jesse@swank.ca" to a regular expression
 * like (^|\W)jesse\@swank\.ca(\W|$).
 *
 * @author jessewilson
 */
public class StringToRegex {

  private String wordCharacters = "0123456789_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

  public String regexify(String input) {
    StringBuilder result = new StringBuilder();

    for(int c = 0; c < input.length(); c++) {
      char character = input.charAt(c);

      // if this is a word character, it doesn't need escaping
      if(wordCharacters.indexOf(character) != -1) {
        result.append(character);

      // if this isn't a word character, escape it for good measure
      } else {
        result.append("\\");
        result.append(character);
      }
    }

    return result.toString();
  }

  public String makeWholeWordsRegex(String regex) {
    return "(^|\\W)" + regex + "(\\W|$)";
  }

  public boolean isWholeWordsRegex(String processedSearchTerm) {
    return processedSearchTerm.startsWith("(^|\\W)");
  }
}
